package com.eg366.nioLearn.simple;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NioWrite {

	public static void main(String[] args) throws IOException {
		// test01();
		// test02();
		test03();
	}

	private static void test03() throws IOException {
		ByteBuffer bb = ByteBuffer.allocate(10); // [pos=0 lim=10 cap=10]
		bb.put("a".getBytes()); // [pos=1 lim=10 cap=10]
		bb.put("bc".getBytes()); // [pos=3 lim=10 cap=10]
		bb.put("de".getBytes()); // [pos=5 lim=10 cap=10]
		FileOutputStream fos = new FileOutputStream(Thread.currentThread().getContextClassLoader().getResource("")
				.getPath()
				+ "/writenio.txt");
		FileChannel channle = fos.getChannel();
		bb.flip();	// [pos=0 lim=5 cap=10]
		channle.write(bb); // [pos=5 lim=5 cap=10]
		channle.close();
		fos.close();
	}

	private static void test01() throws IOException {
		String message = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
		FileOutputStream fos = new FileOutputStream(Thread.currentThread().getContextClassLoader().getResource("")
				.getPath()
				+ "/writenio.txt");
		FileChannel channle = fos.getChannel();
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		buffer.put(message.getBytes());
		buffer.flip();
		/* 将数据写入缓冲区 */
		channle.write(buffer);
		channle.close();
		fos.close();
	}

	private static void test02() throws IOException {
		String message = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
		FileOutputStream fos = new FileOutputStream(Thread.currentThread().getContextClassLoader().getResource("")
				.getPath()
				+ "/writenio.txt");
		FileChannel channle = fos.getChannel();
		/* 将数据写入缓冲区 */
		channle.write(ByteBuffer.wrap(message.getBytes())); // [pos=0 lim=52
															// cap=52]
		channle.close();
		fos.close();
	}
}